
from machine import I2C,SPI,Pin,Timer
from micropython import const
import time
from esp32_ble import  ESP32_BLE
from esp32_wifi import esp32_wifi
from ahtx0 import AHT20,ahtx_interval
from st7735 import ST7735,color
from ws2812 import WS2812
from DateTime import datetime

spi = SPI(2,
                  baudrate=20000000,
                  polarity=0,
                  phase=0,
                  sck=Pin(4),
                  mosi=Pin(5),
                  miso=None)

# 定义控制引脚
dc = Pin(7,Pin.OUT)
cs = Pin(15,Pin.OUT)
rst= Pin(6,Pin.OUT)
#bl = Pin(9, Pin.OUT)
# 初始化显示屏 (128x160)
tft = ST7735(128, 160, spi, dc, cs, rst,None,rotate=0)

i2c = I2C(0,scl=Pin(1),sda=Pin(2),freq=200000)
aht20_sensor = AHT20(i2c)

pin = Pin(48, Pin.OUT)   #配置GPIO8为输出端口，控制ws2812灯珠的DIN信号
wsled = WS2812(pin,1,3,1)

MOINTOR_Interval = const(100)
AHT20_Interval = const(60000)
DateTime_Interval = const(1000)
Weather_Interval = const(1000 * 60  * 10)
WS2812_Interval = const(500)

dt_interval = 0
weather_interval = 0
chgWeatherInfoDisplay = False
chgAht20Display = False
chgDateTimeDisplay = False
chgWS2812Status = False

def GetWeatherInfo(location,interval = 0):
    if wlan.check_wifi():
        weatherinfo = wlan.GetWeather(location,interval)
        if  weatherinfo != False:
            weathertxt = weatherinfo['results'][0]['location']['name']+"天气：" + weatherinfo['results'][0]['now']['text'] + " 温度：" + weatherinfo['results'][0]['now']['temperature'] + " ℃"
#            print(weathertxt)
            tft.showstring(weathertxt,0,100,color(0,0xff,0))
    
def monitor(t):
    global ahtx_interval,dt_interval,weather_interval
    dt_interval += 1
    if dt_interval >= (DateTime_Interval / MOINTOR_Interval):
        dt_interval = 0
        chgDateTimeDisplay = True
        
    if wlan.lasttime_weather is not None:
        weather_interval += 1
    if weather_interval >= (Weather_Interval / MOINTOR_Interval):
        weather_interval = 0
        chgWeatherInfoDisplay = True
#        GetWeatherInfo("shenzhen",1800)
    
    wsled.ws2812_interval += 1
    if wsled.ws2812_interval >= (WS2812_Interval / MOINTOR_Interval):
         wsled.ws2812_interval = 0
         chgWS2812Status = True
#    wsled.ws2812_LED_Cycle()
    ahtx_interval += 1
    if ahtx_interval >= (AHT20_Interval / MOINTOR_Interval):
        ahtx_interval = 0
        chgAht20Display = True

#        print("实测温湿度：\n温度 : {:>4.1f} ℃\n湿度 : {:>4.1f} %".format(wendu,shidu))

    command = ble.get_rec_cmd()
    if command == 'LED ON':
        wsled.ws2812_Power(1)
#            print(ble.ble_msg)
        ble.send('LED is ON.')
#            ble.ble_msg = ''
    # 关闭LED
    elif command == 'LED OFF':
        wsled.ws2812_Power(0)
#        print('LED is OFF.')
        ble.send('LED is OFF.')
#            ble.ble_msg = ''
 

def     button_handler(pin):
    time.sleep_ms(10)	#消除抖动
    if pin.value() == 0:
        wsled.ws2812_Change_Status()

if __name__ == "__main__":
    
    pbootkey = Pin(0, Pin.IN,Pin.PULL_UP) #配置GPIO0为输入端口
    pbootkey.irq(trigger = Pin.IRQ_FALLING,handler=button_handler)
    
    ble = ESP32_BLE("913 AI App")
    dt = datetime()
    tft.clear()
#    wendu = aht20_sensor.temperature
#    shidu = aht20_sensor.relative_humidity
#    tft.showstring("实测温湿度：\n温度 : {:>4.1f} ℃\n湿度 : {:>4.1f} %".format(wendu,shidu),0,42,color(0,0,0xff))
#    tft.showstring("日期 " + dt.format_date() + "时间 " + dt.format_time(),0,2,color(0xF8,0,0))
    wlan = esp32_wifi()
    tim = Timer(3)
    tim.init(period = MOINTOR_Interval,mode=Timer.PERIODIC,callback=monitor)
    PowerOn = True
#    time.sleep(2)
#    wlan.configwifi("weald2000","fkepln_730401")
#    wlan.save_wificonfig()
    while True:
        if wlan.check_wifi():
            if wlan.lasttime_weather is None:
                GetWeatherInfo("shenzhen",1800)

        wlan.periodic_time_sync(3600)
        if  chgDateTimeDisplay or PowerOn:
            chgDateTimeDisplay = False
#            print ("日期 " + dt.format_date() + "时间 " + dt.format_time())
            tft.showstring("日期 " + dt.format_date() + "时间 " + dt.format_time(),0,2,color(0xF8,0,0))
        
        if chgWeatherInfoDisplay:
            chgWeatherInfoDisplay = False
            GetWeatherInfo("shenzhen",1800)
            
        if chgAht20Display or PowerOn:
            chgAht20Display = False
            wendu = aht20_sensor.temperature
            shidu = aht20_sensor.relative_humidity
            tft.showstring("实测温湿度：\n温度 : {:>4.1f} ℃\n湿度 : {:>4.1f} %".format(wendu,shidu),0,42,color(0,0,0xff))        

        if chgWS2812Status or PowerOn:
            wsled.ws2812_LED_Cycle()
        PowerOn = False